package com.example.administrator.text.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.example.administrator.text.HomeActivity;
import com.example.administrator.text.R;
import com.example.administrator.text.WebViewActivity;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import org.apache.log4j.Logger;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import butterknife.Bind;
import butterknife.ButterKnife;
import data.SharedPreferencesUtils;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.JumpActivityUtils;
import util.LogUtil;
import util.NetWorkstateUtil;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;
import util.payUtil.PayUtil;


/**
 * 目前就是 微信支付 结果的回调
 */
public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {
    private IWXAPI api;
    private Logger mLogger = Logger.getLogger(PayUtil.class);

    @Bind(R.id.frame_web_wxpay)    FrameLayout mFrameLayout;
    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wxpay);
        ButterKnife.bind(this);
        api = WXAPIFactory.createWXAPI(this, "wx7e6aad647ba8afa1");
        api.handleIntent(getIntent(), this);
        HomeUtil.getHemeUtilNew().getStatusBar(this,mFrameLayout);
        LogUtil.eE("string","wxapi-WXPayEntryActivity   onCreate（）进来");

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override public void onReq(BaseReq baseReq) {

    }

    @Override public void onResp(BaseResp baseResp) {

        LogUtil.eE("string","wxapi-WXPayEntryActivity"+baseResp.errStr+"     "+baseResp.errCode);
        if (baseResp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            //支付返回的结果 0 表示成功  -1可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等。 -2用户取消
            String string = (String)SharedPreferencesUtils.getParam(WXPayEntryActivity.this,PayUtil.PAY_ORSER,"");
            if(baseResp.errCode == 0){
                getQueryPay(string);
            }else {
                getQueryPay(string);
            }
        }
    }

    /**
     * 微信支付结果的查询
     */
    public void getQueryPay(String order){
        Map<String,Object> map = new HashMap<>();
        map.put("order_id",order);
        map.put("Oid","0433536409");
        mLogger.info("getQueryPay()---微信支付结果查询--order--"+order);
        GreenTreeNetworkUtil.getInstance().doGet(Url.mWINATIAIRIP + Url.WFQ_QUERY,map,new RequestDataCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    mLogger.info("getQueryPay()---微信>onSuccess()--String--"+response);
                    Intent intent = new Intent();
                    intent.setAction(WebViewActivity.mAction);
                    intent.putExtra("pay","WXPAY");
                    sendBroadcast(intent);
                    JSONObject jsonObject = new JSONObject(response);
                    if(jsonObject.getInt("code") == 1){
                        JSONArray jsonArray = jsonObject.getJSONArray("list");
                        if(jsonArray !=null){
                            JSONObject jsonObject1 = (JSONObject) jsonArray.get(0);
                            LogUtil.eE("","jsonObject1.get........."+jsonObject1.getInt("status"));
                            if(jsonObject1.getInt("status") == 2){
                                String commodity = (String) SharedPreferencesUtils.getParam(WXPayEntryActivity.this,PayUtil.PAY_COMMODITY,"");
                                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。 http://123.207.119.229:8080/internet/return_url.jsp
                                if(commodity.equals("会员购买") || commodity.equals("套餐购买")){
                                    SharedPreferencesUtils.setParam(WXPayEntryActivity.this,HomeUtil.mVIPSTATE,true);
                                    EventBus.getDefault().post("vip");
                                }else if(commodity.equals("余额充值")){
                                    JumpActivityUtils.getInstance().jumpWebView(WXPayEntryActivity.this,Url.mATIAIRIP + Url.getUrlNew().WALLET,"我的钱包");
                                }
                                if(commodity.equals("套餐购买") || commodity.equals("时长充值")){
                                    EventBus.getDefault().post("finish");
                                    EventBus.getDefault().post("balance");
                                }
                                if(commodity.equals("会员购买") || commodity.equals("时长充值")){
                                    Intent inten = new Intent(HomeActivity.mAction);
                                    inten.putExtra("wifi","updata_coupon");
                                    sendBroadcast(inten);
                                }
                                finish();
                                Toast.makeText(WXPayEntryActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                            }else {
                                finish();
                                Toast.makeText(WXPayEntryActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                            }
                        }else {
                            finish();
                            Toast.makeText(WXPayEntryActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                        }

                    }else {
                        finish();
                        Toast.makeText(WXPayEntryActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    getBrokenNetwork();

                } catch (JSONException e) {
                    e.printStackTrace();
                    finish();
                    getBrokenNetwork();
                    Toast.makeText(WXPayEntryActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Throwable error) {
                finish();
                getBrokenNetwork();
                mLogger.info("getQueryPay()---支付结果查询--error--"+error);
                Toast.makeText(WXPayEntryActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                StringUtil.getStringUtilNew().getExceptionCode(WXPayEntryActivity.this,error.toString());
            }
        });
    }

    /**
     * 执行断网
     */
    private void getBrokenNetwork(){
        if(Url.getUrlNew().getNETWORKING_ATATE() == 1){
            NetWorkstateUtil.getInstance().getBrokenNetwork(this,null,1);
            Url.getUrlNew().setIsonResumeJudge(false);
            HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Url.getUrlNew().setIsonResumeJudge(true);
                }
            },1500);
        }
    }
}
